package com.zackratos.myandroid.demo02

import androidx.lifecycle.*
import com.zackratos.myandroid.network.Network
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * @Author   : zhangwenchao
 * @Date     : 2020/12/16  9:34 PM
 * @Describe :
 */
class Demo02ViewModel: ViewModel() {

    private val liveData: MutableLiveData<String> by lazy { MutableLiveData<String>() }

    fun observe(owner: LifecycleOwner, observer: Observer<String>) {
        liveData.observe(owner, observer)
    }

    fun request() {
        Network.getInstance().api.baidu().enqueue(object : Callback<ResponseBody> {
            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {

            }

            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                liveData.value = response.body()?.string()
            }
        })
    }

    fun request2() {
        viewModelScope.launch {
            try {
                val body = Network.getInstance().api.baidu2()
                liveData.value = body.string()
            } catch (e: Exception) {
                e.printStackTrace()
                liveData.value = e.message
            }
        }
    }

}